<!-- 分送配置 -->
<template>
  <view>
    <van-popup v-model="showModel" closeable round position="bottom" :style="{ height: '100%' }"
               @click-close-icon="toClose" @click-overlay="toClose">
      <van-row type="flex" justify="center">
        <van-col offset="3" span="8">
          <van-cell value="分送管理" />
        </van-col>
      </van-row>
      <view class="padding-bottom">
        <view>
          <van-cell icon="newspaper-o" title="已分送列表" title-class="text-bold"/>
          <van-row justify="center">
            <van-col span="6">
              <van-cell title="已办环节" title-class="text-bold"></van-cell>
            </van-col>
            <van-col span="6">
              <van-cell title="办理时间" title-class="text-bold"></van-cell>
            </van-col>
            <van-col span="6">
              <van-cell title="当前环节" title-class="text-bold"></van-cell>
            </van-col>
            <van-col span="6">
              <van-cell title="操作" title-class="text-bold"></van-cell>
            </van-col>
          </van-row>
          <van-row justify="center" v-for="item in fsList">
            <template>
              <van-col span="6">
                <van-cell :title="item.fenbanDept"></van-cell>
              </van-col>
              <van-col span="6">
                <van-cell class="flex-wrap" title-class="text-sm" :title="item.banliTime"></van-cell>
              </van-col>
              <van-col span="6">
                <van-cell :title="item.taskNow"></van-cell>
              </van-col>
              <van-col span="6">
                <van-cell title="恢复" v-if="item.state == '办理结束'" @click='getRecoverParam(item.subProInstId)' title-class="text-blue"></van-cell>
                <van-cell title="---" v-else-if="item.workitemSize > 1"></van-cell>
                <van-cell title="撤回" v-else @click='withdraw(item.subProInstId)' title-class="text-blue"></van-cell>
              </van-col>
            </template>
          </van-row>
        </view>
      </view>
      <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }" />
      <view class="padding-bottom">
        <van-cell icon="send-gift-o" title="待分送选择" title-class="text-bold"/>
        <van-collapse accordion :border="false">
          <van-cell is-link title="呈送领导" v-model="formData.praiseUserNames" @click="showforward('1')" />
          <forward ref="csForward" @closeSheet="closeSheet" @saveSheet="saveSheet" :showForward="showForwardCs" :tagType="1" :forwardData="formData"></forward>

          <!--
                    <van-cell is-link title="分送部门" v-model="formData.directDeptNames" @click="showforward('2')" />
                    <forward ref="zbForward" @closeSheet="closeSheet" @saveSheet="saveSheet" :showForward="showForwardZb" :tagType="2" :forwardData="formData"></forward>
          -->

          <van-cell is-link title="分送部门" v-model="formData.copyToDeptNames"  @click="showforward('3')"/>
          <forward ref="xbForward" @closeSheet="closeSheet" @saveSheet="saveSheet" :showForward="showForwardXb" :tagType="3" :forwardData="formData"></forward>
        </van-collapse>
      </view>
      <view class="padding-top-lg padding-bottom-lg">
        <van-row type="flex" justify="space-around">
          <van-col span="10">
            <van-button type="info" round plain hairline block @click="toClose">取消</van-button>
          </van-col>
          <van-col span="10">
            <van-button type="info" round block @click="toSave">分送</van-button>
          </van-col>
        </van-row>
      </view>
    </van-popup>
  </view>
</template>

<script>
import forward from 'pages/caac/components/jnbhDoc/compo-fensong';

export default {
  components: {
    forward,
  },

  props: {
    showSend: {
      type: Boolean,
      default: false
    },
    paramObject: {
      type: Object
    },
    detailObject: {
      type: Object
    },
  },

  data() {
    return {
      showModel: false,
      swForm: {},    // 公文详情
      proInstId: '', // openwfswneededdata接口获取
      configId: '',  // openwfswneededdata接口获取
      proDirId: '',  // openwfswneededdata接口获取
      actInstId: '', // openwfswneededdata接口获取
      actDefId: '',  // openwfswneededdata接口获取
      workitemId: '',// openwfswneededdata接口获取
      dsResult: [], // 是否局长办公室代收
      fsList: [], 		// 已分送单位集合
      showForwardCs: false, // 显示呈送
      showForwardZb: false, // 显示主办
      showForwardXb: false, // 显示协办
      formData: {}, // 提交的数据
      participants: [], // nextActivities中的参数
      initFsDept:{},//初始化分送单位
      recoverParam:{},//恢复接口需要的参数
    };
  },

  watch: {
    showSend(val) {
      this.showModel = val
    },
    paramObject: {
      handler(nval, oval) {
        if (nval != null && JSON.stringify(nval) != "{}") {
          this.proInstId = nval.proInstId
          this.configId = nval.configId
          this.proDirId = nval.proDirId
          this.actInstId = nval.actInstId
          this.actDefId = nval.actDefId
          this.workitemId = nval.workitemId
        }
      },
      immediate: true,
      deep: true
    },
    detailObject: {
      handler(nval, oval) {
        if (nval != null && JSON.stringify(nval) != "{}") {
          this.swForm = nval
          // this.formData.praiseUserNames = nval.praiseUserNames
          // this.formData.praiseUserIds = nval.praiseUserIds
          // this.formData.directDeptNames = nval.directDeptNames
          // this.formData.directDeptIds = nval.directDeptIds
          // this.formData.mainToUserIds = nval.mainToUserIds
          // this.formData.copyToDeptNames = nval.copyToDeptNames
          // this.formData.copyToDeptIds = nval.copyToDeptIds
          // this.formData.copyToUserIds = nval.copyToUserIds
          // 默认将是否局长秘书代收设为0
          this.formData.jzmsDaishou = '0'
        }
      },
      immediate: true,
      deep: true
    },
  },
  mounted() {
    // 初始化单位
    this.initDept()
  },

  methods: {
    // 获取局内便函呈送领导和分送部门
    initAlreadyFs(proInstId) {
      this.$http({
        url: this.$http.adornUrl(`/caac/oa/doc/jbh/listbhfstrack`),
        method: 'get',
        params: this.$http.adornParams({
          'systemKey': this.cache.get('userInfo').systemKey,
          'systemFlag': this.cache.get('userInfo').systemFlag,
          'proInstId': proInstId
        })
      }).then(({data}) => {
        if(data.code==200){
          // 数组
          this.fsList = data.data
          // this.initDept()
          let xbArr =this.initFsDept.zhusong
          let csArr =this.initFsDept.chengsong
          if(this.util.isNotEmpty(this.fsList)){
            this.fsList.forEach((fsItem)=>{//如果已分送出去，则不再显示该单位或领导
              xbArr = xbArr.filter(item => item.deptId != fsItem.clickId)
              csArr = csArr.filter(item => item.userId != fsItem.clickId)
            })
          }
          this.formData.xbList = xbArr
          this.formData.cxList = csArr
          // console.log("------已分送单位-fsList: " + JSON.stringify(data.data));
        }
      })
    },

    // 初始化分送单位
    initDept() {
      this.$http({
        url: this.$http.adornUrl(`/caac/oa/doc/sw/getFensongUserInfo`),
        method: 'get',
        params: this.$http.adornParams({
          'systemKey': this.cache.get('userInfo').systemKey,
          'systemFlag': this.cache.get('userInfo').systemFlag
        })
      }).then(({data}) => {
        // console.log("------初始化分送单位-: " + JSON.stringify(data.data));
        if(data.code==200){

          this.initFsDept = data.data


        }
      })
    },

    // 类型 呈送 主办 协办
    showforward(type){
      if(type == "1" ){
        this.showForwardCs = true
      }else if(type == "2"){
        // 主办只能有一个，主办单位不为空时须先撤回才能再次选择
        if(this.detailObject.mainToUserIds != null && this.detailObject.mainToUserIds != ''){
          this.$toast('先把主办单位撤回后才能进行更换！')
        } else {
          this.showForwardZb = true
        }
      }else if(type == "3"){
        this.showForwardXb = true
      }
    },

    // 关闭sheet
    closeSheet(type) {
      if(type == "1" ){
        this.showForwardCs = false
      }else if(type == "2"){
        this.showForwardZb = false
      }else if(type == "3"){
        this.showForwardXb = false
      }
    },

    // 保存sheet
    saveSheet(data) {
      let type = data.type, result = data.result
      if(type == "1" ) {
        this.showForwardCs = false
        let ids = [], names = []
        result.forEach(t => {
          let arr = t.split('_')
          ids.push(arr[0])
          names.push(arr[1])
        })
        this.formData.jzmsDaishou = data.dsResult
        this.formData.praiseUserIds = this.convertData(this.detailObject.praiseUserIds ,ids)
        this.formData.praiseUserNames = this.convertData(this.detailObject.praiseUserNames ,names)
      } else if(type == "2"){
        this.showForwardZb = false
        let arr = result.split('_')
        this.formData.directDeptIds = arr[0]
        this.formData.directDeptNames = arr[1]
        this.formData.mainToUserIds = arr[2]
        // 选中主办后，将该单位从协办中移除
        if(arr[0] != '') {
          this.removeCopyDeptId(arr[0])
        }
      } else if(type == "3"){
        // console.log('---------------result:' + result)
        this.showForwardXb = false
        let ids = [], names = [], userIds = []
        result.forEach(t => {
          let arr = t.split('_')
          ids.push(arr[0])
          names.push(arr[1])
          userIds.push(arr[2])
        })

        this.formData.copyToDeptIds = this.convertData(this.detailObject.copyToDeptIds ,ids)
        this.formData.copyToDeptNames = this.convertData(this.detailObject.copyToDeptNames ,names)
        this.formData.copyToUserIds = this.convertData(this.detailObject.copyToUserIds, userIds)
      }
    },

    convertData(pData, nData) {
      if(pData != null && pData != '') {
        if(nData.length > 0) {
          let n = nData.filter( (t) => pData.indexOf(t) < 0)
          if(n.length > 0) {
            return pData + ',' + n.toString()
          } else {
            return pData
          }
        } else {
          return pData
        }
      } else {
        return nData.toString()
      }
    },

    // 协办移除
    removeCopyDeptId(deptId) {
      let copyDeptId = this.formData.copyToDeptIds
      if(copyDeptId == null || copyDeptId == '' || deptId == '') {
        return
      }
      let copyDeptName = this.formData.copyToDeptNames
      let copyUserId = this.formData.copyToUserIds

      let dept = this.formData.xbList.filter( t => t.deptId == deptId)
      dept = dept.length > 0 ? dept[0] : dept
      let cdId = copyDeptId.split(',').filter( t => t != deptId)
      let cdName = copyDeptName.split(',').filter( t => t != dept.deptName)
      let cuId = copyUserId.split(',').filter( t => t != dept.userId)

      this.formData.copyToDeptIds = cdId.toString()
      this.formData.copyToDeptNames = cdName.toString()
      this.formData.copyToUserIds = cuId.toString()
    },

    // 取消按钮
    toClose(){
      this.$emit('closeSend', this.showModel)
      this.$emit('refreshBtnGroup',true) // 重新加载数据
    },

    // 分送确认框
    toSave(){
      if(this.validateForm()) {
        this.$dialog.confirm({
          confirmButtonColor: '#1989fa',
          title: '系统提示',
          message: '确认分送吗?',
        }).then(() => {
          // 分送
          this.saveSend()
        }).catch(() => {
          // on cancel
        })
      }
    },

    // 校验
    validateForm() {
      // 呈送、主办、协办中至少选一个
      if(this.util.isEmpty(this.formData.praiseUserIds) && this.util.isEmpty(this.formData.copyToUserIds)) {
        this.$toast('请选择一个局领导或部门')
        return false
      }
      return true
    },

    // 分送
    saveSend(){
      this.$httploading({
        url: this.$http.adornUrl(`/caac/oa/doc/jbh/dofb`),
        method: 'post',
        params:this.$http.adornParams({
          'systemKey': this.cache.get('userInfo').systemKey,
          'systemFlag': this.cache.get('userInfo').systemFlag,
        }),
        data: this.$http.adornData({
          'jzmsDaishou': this.formData.jzmsDaishou,
          'csld': this.formData.praiseUserIds,
          'fsDept': this.formData.copyToDeptIds,// 选择的主办
          'title': this.swForm.title,
          'bizId': this.swForm.fwId,
          'proInstId': this.swForm.proInstId
        })
      }).then(({data}) => {
        // console.log("--------------分送-data-->>: " + JSON.stringify(data));
        if(data.code==200){
          this.$toast('分送成功')
          //pc 接口可能存在延迟，不能及时更新，所以延迟500毫秒再调接口
          this.initDept()//回显值控制
          setTimeout(()=>{
            this.initAlreadyFs(this.proInstId)
            // this.toClose()
          },500)
          //发送成功后置空表单
          this.formData.praiseUserIds = ''
          this.formData.praiseUserNames = ''
          this.formData.copyToDeptNames = ''
          this.formData.copyToUserIds = ''
          this.formData.copyToDeptIds = ''
        }else{
          this.$toast(data.message+' code:'+data.code)
        }
      })
    },

    // 获取调用恢复接口需要的参数
    getRecoverParam(subProInstId){
      this.$httploading({
        url: this.$httploading.adornUrl(`/caac/oa/mywork/selectparambyproinstid/`+subProInstId),
        method: 'get',
        params: this.$httploading.adornParams({
          'systemKey': this.cache.get('userInfo').systemKey,
          'systemFlag': this.cache.get('userInfo').systemFlag,
        }),
      }).then(({data}) => {
        if (data.code == 200) {
          console.log("data getRecoverParam: " + JSON.stringify(data));
          //"data":{"proDirId":"bee4efd8f3124798a762d064a3b1c3c6","actDefId":"sms","configId":"f7cf32554bfe40fa8ffac94188dd0977","proInstId":"063fffbee39c4232862620223bce6e29"},
          this.recoverParam = data.data
          this.recovery()
        } else {
          this.$toast(data.message + ' code:' + data.code)
        }
      })
    },
    // 恢复
    recovery(){
      this.$dialog.confirm({
        confirmButtonColor: '#1989fa',
        title: '系统提示',
        message: '确认恢复吗?',
      })
          .then(() => {
            this.$httploading({
              url: this.$httploading.adornUrl(`/caac/oa/component/workflow/workflowController/reviveprocess`),
              method: 'post',
              params: this.$httploading.adornParams({
                'systemKey': this.cache.get('userInfo').systemKey,
                'systemFlag': this.cache.get('userInfo').systemFlag,
                'data': JSON.stringify({
                  "configId": this.recoverParam.configId,
                  "proDirId": this.recoverParam.proDirId,
                  "proInstId": this.recoverParam.proInstId,
                  "actDefId":this.recoverParam.actDefId,
                  "workItemId":this.workItemId,
                  "actInstId": this.actInstId
                })
              }),
            }).then(({data}) => {
              if (data.code == 200) {
                //{"code":200,"data":{"message":"恢复成功！"},"message":null}
                // 撤回后回显
                this.$toast(data.data.message)
                this.initAlreadyFs(this.proInstId)

              } else {
                this.$toast(data.message + ' code:' + data.code)
              }
            })
          })
          .catch(() => {
            // on cancel
          })
    },
    // 撤回
    withdraw(subProInstId) {
      this.$dialog.confirm({
        confirmButtonColor: '#1989fa',
        title: '系统提示',
        message: '确认撤回吗?',
      })
          .then(() => {
            this.$httploading({
              url: this.$httploading.adornUrl(`/caac/oa/doc/jbh/remove`),
              method: 'post',
              params: this.$httploading.adornParams({
                'systemKey': this.cache.get('userInfo').systemKey,
                'systemFlag': this.cache.get('userInfo').systemFlag,
                'data': JSON.stringify({
                  "configId": this.configId,
                  "subProInstId": subProInstId,
                  "proDirId": this.proDirId,
                  "proInstId": this.proInstId,
                  "actInstId": this.actInstId
                })
              }),
            }).then(({data}) => {
              if (data.code == 200) {
                // 撤回后回显
                this.initAlreadyFs(this.proInstId)

              } else {
                this.$toast(data.message + ' code:' + data.code)
              }
            })
          })
          .catch(() => {
            // on cancel
          })
    },

  },

}
</script>

<style>
.action{
  width: auto !important;
  max-width: 150rpx !important;
}

.van-checkbox--horizontal {
  margin-right: 2px;
}

/deep/ .van-grid-item__content {
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  flex-direction: column;
  box-sizing: border-box;
  height: 100%;
  padding: 10px 8px;
  background-color: #fff;
}
</style>
